import { onMessage, sendMessage } from 'webext-bridge/background'
import { storage } from 'webextension-polyfill'
import { StorageSerializers } from '@vueuse/core'
import type { ExtensionAuthState } from '~/types/auth'

// 安全验证认证状态的函数
function validateAndFixAuthState(authState: ExtensionAuthState | null): ExtensionAuthState | null {
  if (!authState || typeof authState !== 'object') {
    return null
  }

  // 创建一个安全的副本
  const safeAuthState: ExtensionAuthState = {
    domain: authState.domain || 'unknown',
    expiry: authState.expiry || 0,
    loginUrl: authState.loginUrl || '',
    status: authState.status || 'unauthenticated',
    timestamp: authState.timestamp || Date.now(),
    isAuthenticated: Boolean(authState.isAuthenticated),
    user: authState.user,
    token: authState.token || null,
    lastSync: authState.lastSync || Date.now(),
    source: authState.source || 'none',
  }
  return safeAuthState
}

// Background Script 认证处理器
export class BackgroundAuthHandler {
  private currentAuthState: ExtensionAuthState | null = null

  constructor() {
    this.init()
  }

  public init() {
    // 初始化时清理可能损坏的数据
    this.cleanupCorruptedData()

    // 初始化时从存储加载认证状态
    this.loadAuthFromStorage()

    // 设置消息监听器
    this.setupMessageHandlers()
  }

  // 清理损坏的认证数据
  private async cleanupCorruptedData() {
    try {
      // console.warn('🧹 开始清理可能损坏的认证数据...')

      // 清除可能损坏的认证状态
      await storage.local.remove('auth_state')

      // 清除其他可能相关的存储
      const allItems = await storage.local.get()
      const keysToRemove = []

      for (const [key, value] of Object.entries(allItems)) {
        if (key.includes('auth') || key.includes('user')) {
          try {
            // 尝试验证数据结构
            if (typeof value === 'object' && value !== null) {
              if ('user' in value && value.user && typeof value.user === 'object') {
                // 检查用户对象是否有问题
                const userObj = value.user as Record<string, unknown>
                if (typeof userObj.id === 'undefined' || userObj.id === null) {
                  keysToRemove.push(key)
                }
              }
            }
          }
          catch {
            keysToRemove.push(key)
          }
        }
      }

      if (keysToRemove.length > 0) {
        await storage.local.remove(keysToRemove)
        // console.warn(`🧹 清理了 ${keysToRemove.length} 个损坏的存储项:`, keysToRemove)
      }

      // console.warn('✅ 认证数据清理完成')
    }
    catch (error) {
      console.error('❌ 清理认证数据失败:', error)
    }
  }

  // 从存储加载认证状态
  private async loadAuthFromStorage() {
    try {
      const result = await storage.local.get('auth_state')
      if (result.auth_state) {
        const rawAuthState = result.auth_state as ExtensionAuthState

        // 使用安全验证函数
        const validatedAuthState = validateAndFixAuthState(rawAuthState)

        if (validatedAuthState) {
          this.currentAuthState = validatedAuthState
          // console.warn('✅ 从存储加载认证状态:', this.currentAuthState)
        }
        else {
          // console.warn('⚠️ 存储的认证状态数据格式无效，清除状态')
          this.currentAuthState = null
          await storage.local.remove('auth_state')
        }
      }
    }
    catch (error) {
      console.error('❌ 从存储加载认证状态失败:', error)
      this.currentAuthState = null
    }
  }

  // 保存认证状态到存储
  private async saveAuthToStorage(authState: ExtensionAuthState) {
    try {
      // 在保存前验证数据
      const validatedAuthState = validateAndFixAuthState(authState)
      if (validatedAuthState) {
        const serialized = await StorageSerializers.object.write(validatedAuthState)
        await storage.local.set({ auth_state: serialized })
        this.currentAuthState = validatedAuthState
      }
      else {
        throw new Error('认证状态数据无效')
      }
    }
    catch (error) {
      console.error('❌ 保存认证状态失败:', error)
    }
  }

  // 设置消息处理器
  public setupMessageHandlers() {
    // 处理登录消息
    onMessage('auth-login', async ({ data }: { data: any }) => {
      // console.log('🔑 Background auth-login 收到登录消息:', data)
      try {
        // 验证数据完整性
        if (!data || typeof data !== 'object') {
          return { success: false, error: '认证数据格式无效' }
        }

        if (data.status === 'authenticated' && data.token) {
          // 验证用户数据 - 更严格的类型检查
          const user = data.user || null
          const authState: ExtensionAuthState = {
            domain: data.domain || 'unknown',
            expiry: data.expiry || 0,
            loginUrl: data.loginUrl || '',
            status: data.status || 'unauthenticated',
            timestamp: data.timestamp || Date.now(),
            isAuthenticated: true,
            user,
            token: data.token,
            lastSync: Date.now(),
            source: 'content-script',
          }

          await this.saveAuthToStorage(authState)
          // 通知所有组件
          // this.broadcastAuthState(authState)

          // 返回当前认证状态
          const currentAuthState = this.getCurrentAuthState()
          return { success: true, data: currentAuthState }
        }

        return { success: false, error: '无效的认证数据' }
      }
      catch (error) {
        console.error('❌ 处理登录消息时发生错误:', error)
        return { success: false, error: '处理登录消息失败' }
      }
    })

    // 处理登出消息
    onMessage('auth-logout', async () => {
      try {
        console.warn('🚪 Background 收到登出消息')

        const authState: ExtensionAuthState = {
          status: 'unauthenticated',
          timestamp: Date.now(),
          isAuthenticated: false,
          user: null,
          token: null,
          lastSync: Date.now(),
          source: 'content-script',
        }

        await this.saveAuthToStorage(authState)

        // 通知所有组件
        this.broadcastAuthState(authState)

        return { success: true }
      }
      catch (error) {
        console.error('❌ 处理登出消息时发生错误:', error)
        return { success: false, error: '处理登出消息失败' }
      }
    })

    // 处理获取认证状态消息
    onMessage('get-auth-state', async () => {
      return this.currentAuthState
    })

    // 处理刷新认证状态消息
    onMessage('refresh-auth-state', async () => {
      await this.loadAuthFromStorage()
      return this.currentAuthState
    })
  }

  // 广播认证状态到所有组件
  private async broadcastAuthState(authState: ExtensionAuthState) {
    try {
      // 发送到所有上下文（popup, options, sidepanel, content scripts）
      await sendMessage('auth-state-updated', authState, 'popup').catch(() => {
        // popup 可能未打开，忽略错误
      })

      await sendMessage('auth-state-updated', authState, 'options').catch(() => {
        // options 可能未打开，忽略错误
      })

      await sendMessage('auth-state-updated', authState, 'sidepanel').catch(() => {
        // sidepanel 可能未打开，忽略错误
      })

      // 通知所有 content scripts
      await sendMessage('auth-state-updated', authState, 'content-script').catch(() => {
        // content scripts 可能未加载，忽略错误
      })

      // console.warn('📢 认证状态已广播到所有组件')
    }
    catch (error) {
      console.error('❌ 广播认证状态失败:', error)
    }
  }

  // 检查token是否过期
  private isTokenExpired(authState: ExtensionAuthState): boolean {
    if (!authState.isAuthenticated || !authState.lastSync)
      return true

    // 判断 当前时间是否超过了 authState.expiry，如果超过了
    if (!authState.expiry)
      return true

    return Date.now() > authState.expiry
  }

  // 获取当前认证状态
  public getCurrentAuthState(): ExtensionAuthState | null {
    // 使用安全验证函数确保返回的数据是安全的
    return validateAndFixAuthState(this.currentAuthState)
  }

  // 检查认证状态是否有效
  public isAuthenticated(): boolean {
    return this.currentAuthState?.isAuthenticated === true
      && !this.isTokenExpired(this.currentAuthState)
  }

  // 获取当前token
  public getCurrentToken(): string | null {
    if (!this.isAuthenticated())
      return null
    return this.currentAuthState?.token || null
  }
}

// 创建全局实例
export const backgroundAuthHandler = new BackgroundAuthHandler()
